<template>
	<el-dialog
	  :title="!isUpdate ? '新增方案' : '修改方案'"
	  :visible.sync="visible"
	  :before-close="close"
    append-to-body
	  :close-on-click-modal="false"
	  width="30%">
	  <el-form ref="dataForm" :model="dataForm" label-position="top">
      <el-form-item>
        <md-input style="margin-left: 25%;width: 50%;margin-bottom: 50px;" v-model="dataForm.projectName" icon="el-icon-search" placeholder="输入方案名称">
          方案名称
        </md-input>
      </el-form-item>

     <el-form-item label="考察方式">
       <el-select @change="setStabilityMode" value-key="stabilityModeId" v-model="auxForm.stabilityMode" placeholder="考察方式" style="width: 100%;">
         <el-option v-for="m in modeList" :key="m.stabilityModeId" :label="m.stabilityModeName" :value="m" />
       </el-select>
     </el-form-item>

     <el-form-item prop="batchQuantity" label="样品数量">
        <el-input @change="setBatchQuantity" v-model="dataForm.batchQuantity" placeholder="数值(每批量)">
          <el-select @change="setBatchUnit" value-key="unitId" v-model="auxForm.batchUnit" slot="append" placeholder="单位" style="width: 100px;">
            <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item" />
          </el-select>
        </el-input>
     </el-form-item>

     <el-form-item prop="checkPeriodValue" label="检测周期">
        <el-input @change="setCheckPeriodValue" v-model="dataForm.checkPeriodValue" placeholder="数值">
          <el-select @change="setCheckPeriodTime" value-key="timeId" v-model="auxForm.checkPeriodTime" slot="append" placeholder="单位" style="width: 100px;">
            <el-option v-for="t in timeList" :key="t.timeId" :label="t.timeName" :value="t" />
          </el-select>
        </el-input>
     </el-form-item>

     <el-form-item prop="checkFrequency" label="检测频率">
       <span slot="label">
         检测频率: &nbsp;&nbsp;
         <el-button type="text" @click="showProjectTime">(配置样品取样计划)</el-button>
          <el-dialog
            :visible.sync="timeVisible"
            :append-to-body="true"
            width="70%">
           <el-table :data="timeData">
             <el-table-column width="100">
               <template slot="header" slot-scope="{ column, $index }">
                 <el-tooltip content="重置所有" placement="top">
                   <i class="el-icon-refresh point" style="font-size: 18px;color: #D08585;" @click="flushTimeData" />
                 </el-tooltip>
               </template>
               <template slot-scope="scope">
                 <el-button type="warning" class="pan-btn warning-btn" icon="el-icon-plus" @click="addTime(scope.$index)" circle size="mini" />
                 <el-button type="danger" class="pan-btn danger-btn" icon="el-icon-minus" @click="subTime(scope.$index)" circle size="mini" />
               </template>
             </el-table-column>
             <el-table-column width="200" label="取样点">
               <template slot-scope="scope">
                 <el-input @change="setRowTimeValue(scope.$index)" v-model="scope.row.timeValue" placeholder="数值">
                   <el-select @change="setRowTime" value-key="timeId" v-model="auxForm.rowTime" slot="append" placeholder="单位" style="width: 80px;">
                     <el-option v-for="t in timeList" :key="t.timeId" :label="t.timeName" :value="t" />
                   </el-select>
                 </el-input>
               </template>
             </el-table-column>
             <el-table-column label="考察项目">
               <template slot-scope="scope">
                <span style="color: red" class="point" @click="addStandard(scope.$index)" v-if="scope.row.standards.length == 0">请先配置项目<br></span>
                <span style="color: #0071b4" v-else>
                  <span v-for="(s,sindex) in scope.row.standards" :key="sindex">
                    <span style="color: #D4B249" v-html="s.nationInspectionStandardNum + ':'"></span>
                    &nbsp;&nbsp;&nbsp;<span style="color: red" class="point" @click="subStandard(scope.$index, sindex)">删除此标准</span><br>
                    <span class="point" @click="showProjectItem(scope.row, scope.$index, sindex)">{{ s.itemNames }}</span><br>
                  </span>
                  <span class="point" style="color: #67C23A" @click="addStandard(scope.$index)">增加标准</span>
                  <span class="point" style="color: #67C23A" @click="cItem(scope.row)">复制</span>
                </span>
                <span class="point" style="color: #67C23A" @click="vItem(scope.$index)">粘贴</span>
                <span class="point" style="color: #67C23A" @click="vItem">粘贴至全部</span>
                <div v-if="scope.row.standards.length != 0">
                  <span class="point" @click="showSimpleReport(scope.$index)">查看报告配置</span>
                  <span class="point" @click="copyReportToAll(scope.$index)">将此报告配置应用至当前所有取样点</span>
                </div>
               </template>
             </el-table-column>
           </el-table>
           <span slot="footer" class="dialog-footer">
             <el-button type="primary" class="pan-btn primary-btn" size="mini" @click="showProjectTime">确定</el-button>
           </span>
         </el-dialog>
       </span>
        <el-input v-model="dataForm.checkFrequency" placeholder="检测频率"></el-input>
     </el-form-item>

     <el-form-item prop="pack" label="包装">
        <el-input v-model="dataForm.pack" placeholder="包装"></el-input>
     </el-form-item>

     <el-form-item prop="storeEnv" label="贮藏">
        <el-input v-model="dataForm.storeEnv" placeholder="贮藏"></el-input>
     </el-form-item>

     <el-form-item prop="envT" label="温度">
        <el-input v-model="dataForm.envT" placeholder="温度"></el-input>
     </el-form-item>

     <el-form-item prop="envH" label="湿度">
        <el-input v-model="dataForm.envH" placeholder="湿度"></el-input>
     </el-form-item>

     <el-form-item prop="equipmentName" label="设备名称">
        <el-input v-model="dataForm.equipmentName" placeholder="设备名称"></el-input>
     </el-form-item>

     <el-form-item prop="equipmentType" label="设备型号">
        <el-input v-model="dataForm.equipmentType" placeholder="设备型号"></el-input>
     </el-form-item>

     <el-form-item prop="equipmentNum" label="设备编码">
        <el-input v-model="dataForm.equipmentNum" placeholder="设备编码"></el-input>
     </el-form-item>

     <el-form-item prop="remark" label="备注">
        <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
     </el-form-item>
	  </el-form>
	  <span slot="footer" class="dialog-footer">
	    <el-button @click="close">取 消</el-button>
	    <el-button type="primary" class="pan-btn primary-btn" :loading="submiting" @click="submit">确 定</el-button>
  	</span>

    <standard-drawer
      v-if="standardDrawerVisible"
      @close="closeInner('standardDrawerVisible')"
      @getStandard="getStandardObj"
      :childDataForm="grandDataForm" />

    <standard-select
      v-if="standardSelectVisible"
      @close="closeInner('standardSelectVisible')"
      @getStandard="getStandard"
      :childDataForm="grandDataForm" />

    <simple-report
      v-if="simpleReportVisible"
      @close="closeInner('simpleReportVisible')"
      @getSimpleStandards="getSimpleStandards"
      :childDataForm="grandDataForm" />
	</el-dialog>
</template>

<script>
  import { getUnitList } from '@/api/check'
	import {
    saveOrUpdateProject,
    getStabilityModeList,
    getBaseTimeList,
    getProjectInfo,
    getModeTimeList
  } from '@/api/stability'
	import { CODE_OK } from '@/common/js/config'
  import { isPositiveNumber } from '@/common/js/validate'
  import { isBlank } from '@/common/js/utils'
  import StandardDrawer from '@/views/modules/base/standard-drawer'
  import StandardSelect from '@/views/modules/base/standard-select'
  import MdInput from '@/components/MDinput'
  import SimpleReport from '@/views/modules/common/simple-report'
  import { unique } from '@/common/js/utils'
	export default {
		data() {
			return {
        isUpdate: false,
				visible: false,
        timeVisible: false,
        standardDrawerVisible: false,
        standardSelectVisible: false,
        submiting: false,
				dataForm: {},
        standards: [],
        standardForm: {
          standard: '',
          allItems: [],
          checkedItems: []
        },
        auxForm: {
          stabilityMode: '',
          batchUnit: '',
          checkPeriodTime: '',
          rowTime: ''
        },
        modeList: [],
        unitList: [],
        timeList: [],
        timeData: [],
        grandDataForm: "",
        waitIndex: {},
        copyStandards: [],
        simpleReportVisible: false
			}
		},
    components: {
    	StandardDrawer,StandardSelect,MdInput,SimpleReport
    },
		props: ["childDataForm"],
		created() {
			if (!isBlank(this.childDataForm)) {
        this.isUpdate = true
				this.dataForm = this.childDataForm
        this.updateInit()
			}
      this.getInfo()
			this.visible = true
		},
		methods: {
      copyReportToAll(index) {
        this.$confirm('将此份报告的配置(排序、是否打印。。等)应用至当前方案的所有取样点，注意：只能应用当前项目，多余的项目则采用成品报告的缺省配置', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let arr = this.timeData[index].standards
          let baseItems = []
          for (let i=0,j=arr.length; i<j; i++) {
            baseItems.push(...JSON.parse(JSON.stringify(arr[i].items)))
          }
          for (let i=0,j=this.timeData.length; i<j; i++) {
            let t = this.timeData[i]
            for (let m=0,n=t.standards.length; m<n; m++) {
              let s = t.standards[m]
              for (let x=0,y=s.items.length; x<y; x++) {
                let it = s.items[x]
                for (let bi of baseItems) {
                  if (it.inspectionItemId == bi.inspectionItemId) {
                    it.isNumber = bi.isNumber
                    it.printValue = bi.printValue
                    it.isPrint = bi.isPrint
                    it.printConfig = bi.printConfig
                    it.orderId = bi.orderId
                    this.timeData[i].standards[m].items[x] = it
                    break
                  }
                }
              }
            }
          }
          this.$message.success('应用成功')
        }).catch(() => {})
      },
      showSimpleReport(i) {
        this.waitIndex.i = i
        this.grandDataForm = JSON.parse(JSON.stringify(this.timeData[i].standards))
        this.simpleReportVisible = true
      },
      addStandard(i) {
        this.waitIndex.i = i
        this.standardSelectVisible = !this.standardSelectVisible
      },
      subStandard(i, si) {
        this.timeData[i].standards.splice(si, 1)
      },
      vItem(index) {
        if (this.copyStandards.length == 0) {
          this.$message.error("无粘贴项目")
          return
        }else{
          if (typeof(index) == 'number') {
            this.timeData[index].standards = JSON.parse(JSON.stringify(this.copyStandards))
          }else{
            for (let i=0,j=this.timeData.length; i<j; i++) {
              this.timeData[i].standards = JSON.parse(JSON.stringify(this.copyStandards))
            }
          }
        }
      },
      cItem(row) {
        this.copyStandards = JSON.parse(JSON.stringify(row.standards))
        this.$message.success("复制成功，快使用粘贴吧")
      },
      addTime(index) {
        let t = JSON.parse(JSON.stringify(this.timeData[index]))
        t.projectTimeId = null
        t.timeValue = null
        this.timeData.splice(index+1,0,t)
      },
      subTime(index) {
        this.timeData.splice(index,1)
      },
      getStandard(standard) {
        if (standard.nationInspectionStandardNum == null) {
          this.$message.error("此标准不符合规定，无国家标准，请先联系QC管理员(刘威)添加此标准的国家标准")
          return
        }
        this.standardForm.standard = standard
        this.standardForm.allItems = standard.items
        let sList = this.timeData[this.waitIndex.i].standards
        for (let i=0,j=sList.length; i<j; i++) {
          if (standard.insideInspectionStandardId == sList[i]) {
            this.$message.error("不允许有重复标准出现")
            return
          }
        }
        this.standards.push(JSON.parse(JSON.stringify(standard)))
        this.$set(standard, 'itemNames', '')
        this.timeData[this.waitIndex.i].standards.push(standard)
        this.waitIndex.si = sList.length - 1
        this.standardSelectVisible = false
        this.showStandardDrawer()
      },
      closeInner(val) {
        this[val] = false
      },
      getStandardObj(standardObj) {
        let standardId = this.standardForm.standard.insideInspectionStandardId
        let nationInspectionStandardNum = this.standardForm.standard.nationInspectionStandardNum
        let items = standardObj.checkedItems.map(i => {
          this.$set(i, 'insideInspectionStandardId', standardId)
          this.$set(i, 'nationInspectionStandardNum', nationInspectionStandardNum)
          return i
        })
        this.timeData[this.waitIndex.i].standards[this.waitIndex.si].items = items
        this.timeData[this.waitIndex.i].standards[this.waitIndex.si].itemNames = items.map(i => {
          return i.inspectionItemName
        }).join('、')
      },
      getSimpleStandards(standards) {
        this.timeData[this.waitIndex.i].standards = standards
        this.$message.info('修改成功，请提交')
      },
      showProjectItem(row, index, sindex) {
        this.waitIndex = {
          i: index,
          si: sindex
        }
        for (let i=0,j=this.standards.length; i<j; i++) {
          if (row.standards[sindex].insideInspectionStandardId == this.standards[i].insideInspectionStandardId) {
            this.standardForm.standard = this.standards[i]
            this.standardForm.allItems = this.standards[i].items
            this.standardForm.checkedItems = row.standards[sindex].items
            break
          }
        }
        this.showStandardDrawer()
      },
      showStandardDrawer() {
        this.grandDataForm = {
          standard: this.standardForm.standard,
          allItems: this.standardForm.allItems,
          checkedItems: this.standardForm.checkedItems
        }
        this.standardDrawerVisible = true
      },
      showProjectTime() {
        if (isBlank(this.dataForm.stabilityModeId)) {
          this.$message.error("请先选择考察方式")
          return
        }
        if (this.timeData.length == 0) {
          this.getTimeData()
        }
        this.timeVisible = !this.timeVisible
        if (!this.timeVisible) {
          this.setCheckFrequency()
        }
      },
      getInfo() {
        getStabilityModeList().then(res => {
          if (res.code === CODE_OK) {
            this.modeList = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
        getUnitList().then(res => {
          if (res.code === CODE_OK) {
            this.unitList = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
        getBaseTimeList().then(res => {
          if (res.code === CODE_OK) {
            this.timeList = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      getTimeData() {
        if (this.isUpdate) {
          const params = {
            projectId: this.dataForm.projectId
          }
          getProjectInfo(params).then(res => {
            if (res.code === CODE_OK) {
              this.standards = res.info.standards
              this.timeData = res.info.times.map(t => {
                t.standards = t.standards.map(s => {
                  this.$set(s,'itemNames',s.items.map(it => {
                    return it.inspectionItemName
                  }).join('、'))
                  return s
                })
                return t
              })
              this.timeUnitInit()
            }else{
              this.$message.error(res.msg)
            }
          })
        }else{
          this.flushTimeData()
        }
      },
      flushTimeData() {
        const params = {
          stabilityModeId: this.dataForm.stabilityModeId
        }
        getModeTimeList(params).then(res => {
          if (res.code === CODE_OK) {
            this.timeData = res.list.map(t => {
              this.$set(t,'standards',[])
              return t
            })
            this.timeUnitInit()
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      timeUnitInit() {
        this.auxForm.rowTime = {
          timeId: this.timeData[0].timeId,
          timeName: this.timeData[0].timeName
        }
      },
			close(val) {
        if (val == 'submit') {
          this.$emit('refreshData')
        }
				this.$emit('close')
				this.visible = false
			},
      updateInit() {
        this.auxForm.stabilityMode = {
          stabilityModeId: this.dataForm.stabilityModeId,
          stabilityModeName: this.dataForm.stabilityModeName
        }
        this.auxForm.batchUnit = {
          unitId: this.dataForm.batchUnitId,
          unitName: this.dataForm.batchUnitName
        }
        this.auxForm.checkPeriodTime = {
          timeId: this.dataForm.checkPeriodTimeId,
          timeName: this.dataForm.checkPeriodTimeName
        }
      },
			submit() {
        // this.submiting = true
        this.timeData = this.timeData.map(t => {
          t.items = []
          for (let i=0,j=t.standards.length; i<j; i++) {
            for (let x=0,y=t.standards[i].items.length; x<y; x++) {
              t.items.push(t.standards[i].items[x])
            }
          }
          return t
        })
        if (this.formVerify()) {
          for (let i=0,j=this.timeData.length; i<j; i++) {
            this.$set(this.timeData[i],'pitems',this.timeData[i].items)
          }
          const data = {
            project: this.dataForm,
            times: this.timeData
          }
          saveOrUpdateProject(data).then(res => {
            if (res.code === CODE_OK) {
              this.$message.success('添加成功')
              this.close('submit')
            }else{
              this.$message.error(res.msg)
              this.submiting = false
            }
          })
        }else{
          this.submiting = false
        }
			},
      formVerify() {
        //dataForm
        if (isBlank(this.dataForm.projectName)) {
          this.$message.error("随便起一个名字？")
          return false
        }
        if (isBlank(this.dataForm.stabilityModeId)) {
          this.$message.error("请选择考察方式")
          return false
        }
        if (isBlank(this.dataForm.batchQuantity)) {
          this.$message.error("请输入样品数量(数值)")
          return false
        }
        if (isBlank(this.dataForm.batchUnitId)) {
          this.$message.error("请选择样品数量(单位)")
          return false
        }
        if (isBlank(this.dataForm.checkPeriodValue)) {
          this.$message.error("请输入检测周期(数值)")
          return false
        }
        if (isBlank(this.dataForm.checkPeriodTimeId)) {
          this.$message.error("请选择检测周期(单位)")
          return false
        }
        if (isBlank(this.dataForm.checkFrequency)) {
          this.$message.error("检测频率不能为空")
          return false
        }
        if (isBlank(this.dataForm.pack)) {
          this.$message.error("请输入包装")
          return false
        }
        if (isBlank(this.dataForm.storeEnv)) {
          this.$message.error("请输入贮藏")
          return false
        }
        if (isBlank(this.dataForm.envT)) {
          this.$message.error("请输入温度")
          return false
        }
        if (isBlank(this.dataForm.envH)) {
          this.$message.error("请输入湿度")
          return false
        }
        //time
        if (this.timeData.length == 0) {
          this.$message.error("请配置样品取样计划")
          return false
        }
        for (let i=0,j=this.timeData.length; i<j; i++) {
          let t = this.timeData[i]
          if (isBlank(t.timeValue)) {
            this.$message.error("任一个取样点(数值)不能为空")
            return false
          }
          if (isBlank(t.timeId)) {
            this.$message.error("任一个取样点(单位)不能为空")
            return false
          }
          if (t.items.length == 0) {
            this.$message.error("任一个取样点的配置项目不能为空")
            return false
          }
        }
        return true
      },
      //set
      setStabilityMode() {
        this.dataForm.stabilityModeId = this.auxForm.stabilityMode.stabilityModeId
        this.dataForm.stabilityModeName = this.auxForm.stabilityMode.stabilityModeName
        this.getTimeData()
      },
      setBatchQuantity() {
        if (!isPositiveNumber(this.dataForm.batchQuantity)) {
          this.$message.error('请输入正数值类型')
          this.dataForm.batchQuantity = null
        }
      },
      setBatchUnit() {
        this.dataForm.batchUnitId = this.auxForm.batchUnit.unitId
        this.dataForm.batchUnitName = this.auxForm.batchUnit.unitName
      },
      setCheckPeriodValue() {
        if (!isPositiveNumber(this.dataForm.checkPeriodValue)) {
          this.$message.error('请输入正数值类型')
          this.dataForm.checkPeriodValue = null
        }
      },
      setCheckPeriodTime() {
        this.dataForm.checkPeriodTimeId = this.auxForm.checkPeriodTime.timeId
        this.dataForm.checkPeriodTimeName = this.auxForm.checkPeriodTime.timeName
      },
      setRowTimeValue(index) {
        if (!isPositiveNumber(this.timeData[index].timeValue)) {
          this.$message.error('请输入正数值类型')
          this.timeData[index].timeValue = null
        }else{
          this.setCheckFrequency()
        }
      },
      setRowTime() {
        for (let i=0,j=this.timeData.length; i<j; i++) {
          this.timeData[i].timeId = this.auxForm.rowTime.timeId
          this.timeData[i].timeName = this.auxForm.rowTime.timeName
        }
        this.setCheckFrequency()
      },
      setCheckFrequency() {
        if (this.timeData.length == 0) return
        let timeValueStr = this.timeData.map(t => {
          return t.timeValue
        }).join('、')
        let val = '于第' + timeValueStr + this.auxForm.rowTime.timeName + this.auxForm.rowTime.timeName + '末取样检测'
        this.$set(this.dataForm,'checkFrequency',val)
      }
    }
	}
</script>

<style>
</style>
